package com.shxy.controller;

import com.alibaba.fastjson.JSONObject;
import com.shxy.common.ApiResult;
import com.shxy.common.ResultCode;
import com.shxy.controller.ui.LoginBean;
import com.shxy.controller.ui.UserBean;
import com.shxy.entity.User;
import com.shxy.entity.common.enums.RoleEnum;
import com.shxy.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    /**
     * 用户登录
     * @param login
     * @return
     */
    @PostMapping("/login")
    public ApiResult login(@Validated @RequestBody LoginBean login) {
        // 1、根据账号获取用户
        User user = userService.getUserByIdCard(login.getUsername());
        // 2、如果账号不存在
        if(user == null) {
            return ApiResult.fail(ResultCode.USER_ACCOUNT_NOT_EXIST);
        }
        // 3、如果密码不对
        if(!user.getPassword().equals(login.getPassword())) {
            return ApiResult.fail(ResultCode.USER_ACCOUNT_PASSWORD_ERROR);
        }

        JSONObject jo = new JSONObject();
        jo.put("token", user.getId());
        return ApiResult.success(jo);
    }

    /**
     * 获取用户信息
     * @param token
     * @return
     */
    @GetMapping("/info")
    public ApiResult info(@RequestParam String token) {
        // 1、根据编号获取用户
        User user = userService.getUserById(token);
        // 2、如果用户不存在
        if(user == null) {
            return ApiResult.fail(ResultCode.USER_ACCOUNT_EXPIRED);
        }

        UserBean u = new UserBean();
        BeanUtils.copyProperties(user, u);
        u.setUsername(user.getEmployee().getName());
        return ApiResult.success(u);
    }

    /**
     * 登出
     * @return
     */
    @PostMapping("/logout")
    public ApiResult logout() {
        return ApiResult.success();
    }

    @GetMapping("/init")
    public ApiResult initUser() {
        List<User> users = userService.initUsers();
        return ApiResult.success(users);
    }
}
